package cn.wolfcode.p2p.website.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.wolfcode.p2p.base.domain.LoginInfo;
import cn.wolfcode.p2p.base.domain.UserInfo;
import cn.wolfcode.p2p.base.domain.VideoAuth;
import cn.wolfcode.p2p.base.exception.DisplayableException;
import cn.wolfcode.p2p.base.service.ILoginInfoService;
import cn.wolfcode.p2p.base.service.IUserInfoService;
import cn.wolfcode.p2p.base.service.IVideoAuthService;
import cn.wolfcode.p2p.base.util.DateUtil;
import cn.wolfcode.p2p.base.util.JSONResult;
import cn.wolfcode.p2p.base.util.UserContext;

/**
 * 前台视频认证控制器
 * 
 * @author wolfcode
 *
 */
@Controller
public class VideoAuthController {

	@Autowired
	private ILoginInfoService logininfoService;

	@Autowired
	private IVideoAuthService authService;

	@Autowired
	private IUserInfoService userinfoService;

	/**
	 * 预约视频认证
	 */
	@RequestMapping("saveVideoAuditOrder")
	@ResponseBody
	public JSONResult order(VideoAuth to) {
		JSONResult result = new JSONResult();
		try {
			this.authService.order(to);
		} catch (DisplayableException ex) {
			result = new JSONResult(false, ex.getMessage());
		} catch (Exception e) {
			// 把错误信息记录到服务器中日志文件中,方便排查问题.
			result = new JSONResult(false, "系统异常,请联系管理员!");
			e.printStackTrace();
		}
		return result;
	}

	/**
	 * 视频认证预约页面
	 */
	@RequestMapping("videoAuditOrder")
	public String videoAuthPage(Model model) {

		UserInfo current = this.userinfoService.get(UserContext.getCurrent().getId());
		if (current.getHasVideoAuth()) {
			model.addAttribute("videoSuccess",true);
		} else {
			if (current.getVideoAuthId() != null) {
				// 有视频申请在审核中
				model.addAttribute("videoAuth", this.authService.get(current.getVideoAuthId()));
			} else {
				// 审核人列表auditors
				List<LoginInfo> auditors = this.logininfoService.listAuditors();
				model.addAttribute("auditors", auditors);

				// 可预约日期列表orderDates
				List<Date> dates = new ArrayList<>();
				Date now = new Date();
				for (int i = 1; i <= 5; i++) {
					dates.add(DateUtil.addDays(now, i));
				}
				model.addAttribute("orderDates", dates);

				// 预约时间段(OrderTime)列表orderTimes
				model.addAttribute("orderTimes", this.authService.listOrderTimes());
			}
		}
		return "videoOrder";
	}

}
